"""商品推广模块"""

import time

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

from shopee.config import CF
from shopee.browser import browser, wait
from shopee.utils import *

EXTENSION_URL = 'https://seller.shopee.com.my/portal/product/list/all'
EXTENSION_COUNT = 0


@tip.register('extension')
@TryExcept(level='warn')
def extension():
    global EXTENSION_COUNT
    EXTENSION_COUNT += 1
    log_print(f'Start of extension {EXTENSION_COUNT}')

    num, extensions2 = len(CF.extensions), CF.extensions.copy()
    # 检查配置文件是否存在推广商品
    if num == 0:
        print('There are no products for promotion!')
        return

    browser.get(EXTENSION_URL)

    # 进度条
    short_rest(time_interval=0.1)

    # 去除tip
    _tip_xpath = '//div[@class="tip-container"]//button'
    _tip = browser.find_elements(By.XPATH, _tip_xpath)
    if len(_tip):
        print('skipping tip1...')
        browser.execute_script("arguments[0].click();", _tip[0])

    # 查看所有商品
    goods = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//tbody/tr')))

    # 遍历所有商品，并与配置文件中需要推广的商品进行对比
    for good in goods:
        flag = False
        good_name_xpath = './/div[@class="product-name-text"]//a/span'
        good_name = good.find_element(By.XPATH, good_name_xpath).text

        for extension_item in extensions2:
            if extension_item in good_name:
                flag, num = True, num - 1
                extensions2.remove(extension_item)
                break

        # 若该商品名不在配置文件的推广列表里，则跳过
        if flag is False:
            continue

        # 进行推广
        more_button_xpath = './/div[@class="more-dropdown shopee-dropdown"]/button'
        more_button = good.find_element(By.XPATH, more_button_xpath)
        browser.execute_script("arguments[0].click();", more_button)
        dropdown_menu_xpath = '//div[@class="shopee-popper more-dropdown-menu"]'
        dropdown_menus = good.find_elements(By.XPATH, dropdown_menu_xpath)
        dropdown_menus = [item for item in dropdown_menus if 'display: none' in item.get_attribute('style')]

        if len(dropdown_menus) == 0:
            continue

        dropdown_menu = dropdown_menus[0]
        extension_button_xpath = './/div[@class="boost-button-text"]'
        extension_buttons = dropdown_menu.find_elements(By.XPATH, extension_button_xpath)

        if len(extension_buttons):
            browser.execute_script("arguments[0].click();", extension_buttons[0])
            print(f'promote goods:{good_name}')

        else:
            print(f'Wait for cooling,goods:{good_name}')

        browser.execute_script("arguments[0].click();", more_button)
        time.sleep(1.5)

        # 若配置文件中的推广列表中的商品全部推广完成,则停止遍历其他商品
        if len(extensions2) == 0:
            break

    # 打印未被推广的商品名
    if len(extensions2):
        for item in extensions2:
            print(f'There is no item matching "{item}" in the listing!')
